const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  formatTime,
  url: {
    uploadPath: "http://localhost/hotel/file/upload",
    sendCode: "http://localhost/auth/open/api/user/email/sendCode",
    register: "http://localhost/auth/open/api/user/register",
    login: "http://localhost/auth/oauth/token",
    getcitys: "http://localhost/hotel/open/api/city/list",
    search: "http://localhost/search/open/api/hotel/search",
    details: "http://localhost/hotel/open/api/hotel/details",
    detailsList: "http://localhost/hotel/open/api/rooms/list",
    orderprices: "http://localhost/hotel/open/api/order/prices",
    couponList: "http://localhost/coupon/coupon/list",
    couponGet: "http://localhost/coupon/coupon/getcoupon",
    couponUserList: "http://localhost/coupon/coupon/listByUser",
    couponUserListByOrders: "http://localhost/coupon/coupon/listByUserOrders"
  },
  myajax: function(obj){
    //显示加载框
    wx.showLoading({
      title: '请求中...',
    });

    //封装一个请求头
    var myheader = {};
    myheader['content-type'] = obj.type ? obj.type : "application/x-www-form-urlencoded";
    //请求来源 2-微信小程序
    myheader.fromType = 2;
    //携带登录令牌
    var accessToken = wx.getStorageSync('accessToken');
    if (accessToken) {
      myheader.Authorization = "Bearer " + accessToken;
    }  

    wx.request({
      method: obj.method ? obj.method : "GET",
      header: myheader,
      url: obj.url,
      data: obj.data ? obj.data : {},
      success: resp => {
        if(resp.data.code == 200){
          if(obj.success){
             //操作成功
            obj.success(resp.data.data);
          } 
        } else if(resp.data.code == 401){
          //操作失败
          wx.showToast({
            title: "账号或密码错误",
            icon: "error"
          })
        } else {
          //操作失败
         wx.showToast({
           title: resp.data.msg,
           icon: "error"
         })
       }
      },
      fail: resp => {
        wx.showToast({
          title: "服务器访问异常，请稍后再试！",
          icon: "error"
        })
      },
      complete: () => {
        //关闭等待框
        wx.hideLoading();
      }
    })
  }
}
